#coding=utf-8
'''
Created on 2013-9-3

@author: Ben

武将管理
'''

from __future__ import division
from ..common import Logger, BasicThread, AIConfig
from ..role import RoleData, FunctionData
from ..util import TimeUtil
from ..world import World, WorldData
import General
import GeneralData
import GeneralVO
import random
import time

#武将管理线程的实例
generalManager = None
#可攻击的城市路线
attackableCityList = [[205, 156, 155, 153, 152, 146, 144, 56,  140, 139, 105,103,97,142,143,138],\
                    [205,161,159,158,157,149,118,116,115,112],\
                    [210,209,204,241,240,239,234,233,232,189,225,227,224]]
#当前选择的城市路线
currentPath = 0
#下一次大睡眠的循环次数
long_sleep_count = 60
#下一次改变城市路线的循环次数
change_path_count = 6

worldGetInfoRequest = None
generalGetInfoRequest = None

def worldGetInfoCallback():
    #领取整点杀敌奖励
    if WorldData.hourKillRewardReceived == 0:
        WorldData.hourKillRewardReceived = 1
        World.getHourKillReward()

def generalGetInfoCheck():
    return GeneralData.refreshGenerals

def generalGetInfoCallback():
    GeneralData.refreshGenerals = False

def start():
    global generalManager
    global worldGetInfoRequest
    global generalGetInfoRequest
    if generalManager == None:
        generalManager = GeneralManager(name="generalManager")
    worldGetInfoRequest = World.WorldGetInfoRequest(None, worldGetInfoCallback, 60, 20)
    generalGetInfoRequest = General.GeneralGetInfoRequest(generalGetInfoCheck, generalGetInfoCallback, 40, 10)
    generalManager.startThread()
    
def pause():
    global generalManager
    if generalManager != None:
        generalManager.pauseThread()

'''
检测是否需要更新数据
'''
def checkDataRefresh():
    global long_sleep_count
    global change_path_count
    global currentPath
    global attackableCityList
    if long_sleep_count == 0:
        time.sleep(60)
        long_sleep_count = TimeUtil.getRandomCount(120, 10)
    else:
        long_sleep_count -= 1
    if change_path_count == 0:
        currentPath = (currentPath + 1) % len(attackableCityList)
        Logger.log("路线切换为" + str(currentPath), output = True)
        change_path_count = TimeUtil.getRandomCount(30, 5)

'''
检测是否需要使用募兵令加速募兵
'''
def checkRecruit(forces, forcesMax):
    speedUp = False
    #募兵令还很多, 果断加速
    if GeneralData.token > AIConfig.recruit_token_upper:
        speedUp = True
    #募兵令不多, 小概率加速
    elif GeneralData.token > AIConfig.recruit_token_lower:
        if forcesMax > 0 and forces / forcesMax < 0.2 and random.random() > 0.8:
            speedUp = True
    return speedUp
    
class GeneralManager(BasicThread.BasicThread):
    
    '''
    检查是否满足攻城的条件
    '''
    def checkAttackable(self):
        #检查时间(24小时都在打会被认为是外挂的)
        currentHour = TimeUtil.getCurrentLocalHour()
        if currentHour >= 24:
            print u'当前时间不适合打城'
            return False
        #检查粮食
        if RoleData.food < RoleData.getAttackStopFood():
            print u'粮食不足'
            return False
        return True
     
    '''
    检查武将状态
    '''
    def checkGeneralState(self, generalId, generalVO):
        #输出武将状态
        Logger.log(str(generalId) + generalVO.getGeneralStateStr(), output = True)
        #武将在牢房
        if generalVO.cState == GeneralVO.C_STATE_PRISON:
            General.escape(generalId)
            return False
        #武将在移动或逃跑
        elif generalVO.cState == GeneralVO.C_STATE_MOVE \
        or generalVO.cState == GeneralVO.C_STATE_ESCAPE:
            return False
        #武将在募兵
        elif generalVO.generalState == GeneralVO.GENERAL_STATE_RECRUIT:
            #如果可以使用募兵令
            if checkRecruit(generalVO.forces, generalVO.forcesMax):
                General.tokenRecruit(generalId)
                time.sleep(TimeUtil.getRandomTime(3, 1))
            else:
                return False
        #武将不在空闲状态
        elif generalVO.generalState != GeneralVO.GENERAL_STATE_FREE \
        or generalVO.cState != GeneralVO.C_STATE_FREE:
            return False
        return True
       
    def addGeneralToList(self, generalId, generalIdList):
        if generalId > 0:
            generalVO = GeneralData.getGeneralVO(generalId)
            if self.checkGeneralState(generalId, generalVO) and generalId not in generalIdList:
                generalIdList.append(generalId)
    
    def callback(self):
        time.sleep(TimeUtil.getRandomTime(20, 10))
        #检查世界是否开放
        if FunctionData.func10 == 0:
            return
        #检查是否满足攻城条件
        if not self.checkAttackable():
            time.sleep(60)
            return
        #基本检查
        checkDataRefresh()
        #刷新世界
        global worldGetInfoRequest
        if worldGetInfoRequest.run():
            return
        #刷新武将
        global generalGetInfoRequest
        if generalGetInfoRequest.run():
            return
        
        generalIdList = []
        #获取攻城武将
        if(AIConfig.attack_generals and len(AIConfig.attack_generals) > 0):
            for generalName in AIConfig.attack_generals:
                generalId = GeneralData.getGeneralIdByPic(generalName)
                self.addGeneralToList(generalId, generalIdList)
        else:
            for gId in GeneralData.generalList:
                self.addGeneralToList(gId, generalIdList)
        #没有满足条件的武将
        if len(generalIdList) <= 0:
            return
        
        #目标城市id
        targetCityId = 0
        targetCityVO = None
        global currentPath
        global attackableCityList
        global change_path_count
        #寻找可以攻击的城市
        for cityId in attackableCityList[currentPath]:
            cityVO = WorldData.getCityVO(cityId)
            #判断是否为敌方势力且可以攻击的
            if cityVO != None and cityVO.belong != 3 and cityVO.attackable:
                targetCityId = cityVO.cityId
                targetCityVO = cityVO
                break
        #目标城市是否存在
        if targetCityId > 0:
            msg = '选择了' + str(targetCityId) + '作为攻击城市, 城市当前所属势力为' + str(targetCityVO.belong)
            Logger.log(msg, output = True)
            change_path_count -= 1
        else:
            Logger.log('没有可以选择的目标城市', output = True)
            #更改路线
            change_path_count = 0
            return
        #移动到目标城市
        for generalId in generalIdList:
            World.startGeneralMove(cityId, generalId)
            time.sleep(1)